import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/delete")
public class deleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断登录状态
        HttpSession session=req.getSession();
        if(session==null){
            resp.setStatus(403);
            resp.sendRedirect("login.html");
            return;
        }
        User user= (User) session.getAttribute("user");
        if (user==null){
            resp.setStatus(403);
            resp.sendRedirect("login.html");
            return;
        }
        String blogId=req.getParameter("blogId");
        if (blogId==null){
            resp.setStatus(403);
            resp.getWriter().write("blogId错误");
            return;
        }
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectById(Integer.parseInt(blogId));
        if(blog==null){
            resp.setStatus(403);
            resp.getWriter().write("blog不存在");
            return;
        }
        if(user.getUserId()!=blog.getUserId()){
            resp.setStatus(403);
            resp.getWriter().write("没有删除权限");
            return;
        }
        blogDao.deleteById(Integer.parseInt(blogId));
        //更新数据库
        UserDao userDao=new UserDao();
        userDao.upDate(-1);
        //更新user
        user.setBlogCount(user.getBlogCount()-1);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }
}
